package com.sanjiahantang.ythshopping.activity.me;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.sanjiahantang.shopping.uilibrary.ClearEditText;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.shopping.uilibrary.views.SideBarView;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.BaseActivity;
import com.sanjiahantang.ythshopping.adapter.NewAreaListAdapter;
import com.sanjiahantang.ythshopping.model.AreaBean;
import com.sanjiahantang.ythshopping.model.AreaModel;
import com.sanjiahantang.ythshopping.presenter.SelectAreaPresenter;
import com.sanjiahantang.ythshopping.utils.SPUtils;
import com.sanjiahantang.ythshopping.utils.Utils;
import com.sanjiahantang.ythshopping.views.SelectAreaView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zy on 2017/9/18.
 */

public class NewAreaListActivity extends BaseActivity implements View.OnClickListener,SelectAreaView, SelectAreaView.CheckPermissionsListener {

    private View back;

    private CheckPermissionsListener mListener;
    private ViewGroup emptyView;
    private ListView mResultListView;
    private ListView listview;
    private SelectAreaPresenter saPresenter;
    private ClearEditText cetSearch;
    private Handler mHandler;
    private SideBarView mLetterBar;
    private NewAreaListAdapter mCityListAdapter;
    private TextView overlay;
    private AMapLocationClient mLocationClient;
    //高德定位所需要的权限
    public static final String KEY_PICKED_CITY = "picked_city";
    protected final String[] neededPermissions = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int REQUEST_CODE = 2;
    List<AreaBean.City> mAllCities,mResultCities;
    private QuickAdapter<AreaBean.City> mResultAdapter;
    private Runnable eChanged;
    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_new_area_list);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        back = findViewById(R.id.rlback);
        back.setOnClickListener(this);
        overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        saPresenter = new SelectAreaPresenter(this);
        mLetterBar = (SideBarView) findViewById(R.id.side_letter_bar);
        listview = (ListView) findViewById(R.id.listview);
        cetSearch = (ClearEditText) findViewById(R.id.cetSearch);
        mResultCities = new ArrayList<>();
        cetSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    listview.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    listview.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.VISIBLE);
                    mHandler.post(eChanged);

                }
            }
        });

        mHandler = new Handler();
        eChanged = new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                String data = cetSearch.getText().toString();

                mResultCities.clear();

                getmDataSub(mResultCities, data);


                if (mResultCities == null || mResultCities.size() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                } else {
                    emptyView.setVisibility(View.GONE);
                    mResultAdapter.clear();
                    mResultAdapter.addAll(mResultCities);
                }
            }
        };

        mResultAdapter = new QuickAdapter<AreaBean.City>(mContext,R.layout.item_area_city) {
            @Override
            protected void convert(BaseAdapterHelper helper, final AreaBean.City item) {
                helper.setVisible(R.id.tv_item_city_listview_letter,false);
                helper.setText(R.id.tv_item_city_listview_name,item.getRegion_name());
                helper.setOnClickListener(R.id.tv_item_city_listview_name, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setResult(2,new Intent().putExtra("city",new Gson().toJson(item)));
                        AreaBean.addHistory(mContext,item);
                        finish();
                    }
                });
            }
        };

        mResultListView.setAdapter(mResultAdapter);

        mLetterBar.setOnLetterSelectListen(new SideBarView.LetterSelectListener() {
            @Override
            public void onLetterSelected(String letter) {
                if(mCityListAdapter != null){
                    int position = mCityListAdapter.getLetterPosition(letter);
                    listview.setSelection(position);
                }
                overlay.setVisibility(View.VISIBLE);
                overlay.setText(letter);
            }

            @Override
            public void onLetterChanged(String letter) {
                if(mCityListAdapter != null){
                    int position = mCityListAdapter.getLetterPosition(letter);
                    listview.setSelection(position);
                }
                overlay.setVisibility(View.VISIBLE);
                overlay.setText(letter);
            }

            @Override
            public void onLetterReleased(String letter) {
                overlay.setVisibility(View.GONE);
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);



    }

    private void getmDataSub(List<AreaBean.City> mDataSubs, String data)
    {
        int length = mAllCities.size();
        for(int i = 0; i < length; ++i){
            if(mAllCities.get(i).getRegion_name().contains(data) || mAllCities.get(i).getPinyin().contains(data.toLowerCase())){
                mDataSubs.add(mAllCities.get(i));
            }
        }
    }

    @Override
    public void initData() {
        super.initData();
        saPresenter.loadNewArea(this, new CallBack() {
            @Override
            public void onSuccess(AreaBean bean) {
//                ToastUtil.showToast(NewAreaListActivity.this,(new Gson().toJson(bean)));
//                new AlertDialog.Builder(NewAreaListActivity.this).setMessage(new Gson().toJson(bean)).show();
//                listview.setAdapter(new AreaAdapter(bean));
                mAllCities = new ArrayList<AreaBean.City>();
                for (int i = 0,max = bean.getData().getPinyin_city().size();i < max;i++){
                    mAllCities.addAll(bean.getData().getPinyin_city().get(i).getCity());
                }
                mCityListAdapter = new NewAreaListAdapter(mContext, mAllCities,bean.getData().getHot_city());
                mCityListAdapter.setOnCityClickListener(new NewAreaListAdapter.OnCityClickListener() {
                    @Override
                    public void onCityClick(AreaBean.City city) {
                        setResult(2,new Intent().putExtra("city",new Gson().toJson(city)));
                        AreaBean.addHistory(mContext,city);
                        finish();
                    }

                    @Override
                    public void onLocateClick() {
                        requestPermissions((Activity) mContext, neededPermissions, NewAreaListActivity.this);
                    }
                });
                listview.setAdapter(mCityListAdapter);

                initLocation();
                //请求权限
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
                    mLocationClient.startLocation();
                }else {
                    requestPermissions((Activity) mContext, neededPermissions, NewAreaListActivity.this);
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rlback:
                finish();
                break;

        }
    }

    @Override
    public void getArea(AreaModel model) {

    }

    public void requestPermissions(Activity activity, String[] permissions, CheckPermissionsListener listener){
        if (activity == null) return;
        mListener = listener;
        List<String> deniedPermissions = findDeniedPermissions(activity, permissions);
        if (!deniedPermissions.isEmpty()){
            ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
        }else{
            //所有权限都已经同意了
            mListener.onGranted();
        }
    }

    private List<String> findDeniedPermissions(Activity activity, String... permissions){
        List<String> deniedPermissions = new ArrayList<>();
        for (String permission : permissions){
            if (ActivityCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED){
                deniedPermissions.add(permission);
            }
        }
        return deniedPermissions;
    }

    @Override
    public void onGranted() {
        mLocationClient.startLocation();
    }

    @Override
    public void onDenied(List<String> permissions) {
        Toast.makeText(this, "权限被禁用，请到设置里打开", Toast.LENGTH_SHORT).show();
        mCityListAdapter.updateLocateState(SelectAreaView.FAILED, null,null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_CODE:
                List<String> deniedPermissions = new ArrayList<>();
                int length = grantResults.length;
                for (int i = 0; i < length; i++){
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED){
                        //该权限被拒绝了
                        deniedPermissions.add(permissions[i]);
                    }
                }
                if (deniedPermissions.size() > 0){
                    mListener.onDenied(deniedPermissions);
                }else{
                    mListener.onGranted();
                }
                break;
            default:
                break;
        }
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        String location = Utils.extractLocation(city, district);
                        String province = aMapLocation.getProvince();
                        if(mCityListAdapter != null){
                            mCityListAdapter.updateLocateState(SelectAreaView.SUCCESS, location,province);
                        }

                    } else {
                        //定位失败
                        if(mCityListAdapter != null){
                            mCityListAdapter.updateLocateState(SelectAreaView.FAILED, null,null);
                        }

                    }
                }
            }
        });
    }
}
